package com.example.db.dynamicdatasource.aop;

import com.example.db.dynamicdatasource.dbutils.DBContextHolder;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author L.xf
 * @date 2021/10/28
 */
@Component
@Aspect
@Order(-1)
public class DataSourceAop {

    /*从库的切点,没有标注Master注解，并且方法名为find和exit开头的方法，走从库*/
    @Pointcut("!@annotation(com.example.db.dynamicdatasource.annotation.Master) " +
            "&& (execution(* org.springframework.data.repository.*.find*(..))" +
            "||execution(* org.springframework.data.repository.*.exist*(..)))")
    public void slavePointcut() {

        // 获取方法名，排除
//        Signature signature = joinPoint.getSignature();
//        MethodSignature methodSignature = (MethodSignature) signature;
//        String methodName = methodSignature.getMethod().getName();

    }

    /*主库的切点,或者标注了Master注解或者方法名为save、delete等开头的方法，走主库
     * */
    @Pointcut("@annotation(com.example.db.dynamicdatasource.annotation.Master) "+
            "|| execution(* org.springframework.data.repository.*.save*(..))" +
            "||execution(* org.springframework.data.repository.*.delete*(..))")
    public void masterPointcut() {

    }

    @Before("slavePointcut()")
    public void slave() {
        DBContextHolder.slave();
    }

    @Before("masterPointcut()")
    public void master() {
        DBContextHolder.master();
    }
}
